<template>
  <ContentDetailWrap :title="t('warehouse.add')">
    <template #header>
      <BaseButton @click="go(-1)">
        {{ t('common.back') }}
      </BaseButton>
      <BaseButton type="primary" :loading="loading" @click="submit(formRef)">
        {{ t('action.save') }}
      </BaseButton>
    </template>
    <!--    表单-->
    <el-form
      class="flex flex-wrap"
      :model="state.form"
      ref="formRef"
      :rules="rules as FormRules"
      label-width="22%"
    >
      <el-form-item :label="t('category.parent_id')" class="w-60%" prop="parent_id">
        <el-select
          v-model="state.form.parent_id"
          filterable
          clearable
          :placeholder="'请选择' + t('category.parent_id')"
        >
          <el-option
            v-for="item in state.first_category_list"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('category.name')" class="w-60%" prop="name" required>
        <el-input v-model="state.form.name" :placeholder="'请输入' + t('category.name')" />
      </el-form-item>
      <el-form-item :label="t('category.description')" class="w-60%" prop="description">
        <el-input v-model="state.form.description" type="textarea" />
      </el-form-item>

      <el-form-item :label="t('category.sort_order')" class="w-60%" prop="sort_order">
        <el-input
          v-model="state.form.sort_order"
          type="number"
          :placeholder="'请输入' + t('category.sort_order')"
        />
      </el-form-item>
      <el-form-item :label="t('category.solution_type')" class="w-60%" prop="solution_type">
        <el-select
          v-model="state.form.solution_type"
          filterable
          :placeholder="'请选择' + t('category.solution_type')"
        >
          <el-option label="是" :value="1" />
          <el-option label="否" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item
        :label="t('category.image')"
        :placeholder="'请输入' + t('category.image')"
        class="w-60%"
      >
        <UploadFile
          class="w-100%"
          url="/common/uploadFile"
          drag
          :file-type="['png', 'jpg', 'jpeg']"
          :params="{ directory: 4 }"
          :limit="1"
          upload-file-button-name="点击上传或拖拽到此处上传"
          buttonWidth="100%"
          :button-link="true"
          :show-file-list="true"
          @upload-success-res="handleUploadImageCallback"
          @handle-remove-file="handleRemoveImageFile"
          @handle-picture-card-preview="handleImagePreview"
        />
      </el-form-item>
    </el-form>
  </ContentDetailWrap>
</template>
<script setup lang="ts">
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ElMessage, type FormRules, type FormInstance } from 'element-plus'

import { saveDataApi, getFirstCategorySelect } from '@/api/category'
import { createImageViewer } from '@/components/ImageViewer'
import { useRouter, useRoute } from 'vue-router'

const { t } = useI18n()
const { push, go } = useRouter()
const route = useRoute()

const loading = ref<boolean>(false)
const formRef = ref<FormInstance>()
const state = reactive({
  source: route.query.source ? decodeURIComponent(route.query.source as string) : '',
  first_category_list: ref<any[]>([]),

  form: ref<Record<string, any>>({
    id: 0,
    name: '',
    description: '',
    sort_order: null,
    image: 0,
    parent_id: null,
    solution_type: 0
  }),
  image_list: ref<any[]>([]), // 附件列表
  closeshots_photo_list: ref<any[]>([]) // 附件列表
})

const tableData = ref<Array<Record<string, any>>>([]) // 表格数据

const rules = ref<FormRules>({
  // parent_id: [
  //   {
  //     required: true,
  //     message: '请选择' + t('category.parent_id'),
  //     trigger: 'change'
  //   }
  // ],
  name: [
    {
      required: true,
      message: '请输入' + t('category.name'),
      trigger: 'blur'
    }
  ]
})

//上传成功以后回调
const handleUploadImageCallback = (val: any) => {
  state.image_list.push(val)
}

const handleRemoveImageFile = (val: any) => {
  if (state.image_list && state.image_list.length) {
    state.image_list = state.image_list.filter((item: Record<string, any>) => {
      item.uploadFile.uid !== val.uid
    })
  }
}

const handleImagePreview = (val: any) => {
  if (!val) return
  createImageViewer({
    urlList: [val],
    zIndex: 99999
  })
}

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      const params = { ...state.form } as unknown as Record<string, any>
      if (state.image_list.length) {
        params.image = state.image_list.map((item: any) => item.id).join(',')
      }
      const resp = await saveDataApi(params)
      if (resp.code === 0) {
        ElMessage.success(t('order.createSucMsg'))
        if (state.source) {
          push(`${state.source}`)
        } else {
          push('/product/category-management')
        }
      }
    }
  })
}

onMounted(() => {
  getFirstCategorySelect().then((res) => {
    state.first_category_list = res.data.list
  })
})
</script>

<style lang="less" scoped>
/* 隐藏 el-radio 的文本标签 */
:deep(.el-radio__label) {
  display: none;
}
</style>
